package com.yunnuo.system.login.controller;

import net.sf.json.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yunnuo.system.comm.util.ResultData;

/**
 * Created by w_weihf on 2018/7/20.
 */
@Controller
public class LoginController {

    /**
     * @api {get} / 系统默认跳转地址
     * @apiName welcome
     * @apiGroup System-logincontroller
     */
    @GetMapping({"/", ""})
    String welcome(Model model) {
        return "redirect:/login";
    }

    /**
     * @api {get} /login  跳转系统登陆
     * @apiName login
     * @apiGroup System-logincontroller
     */
    @GetMapping("/login")
    String login() {
        return "login";
    }

    /**
     * @api {post} /login  系统登陆
     * @apiName login
     * @apiGroup System-logincontroller
     */
    @PostMapping("/login")
    @ResponseBody
    public JSON ajaxLogin(String username, String password) {
        ResultData data = new ResultData();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();


        try {
            subject.login(token);
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("操作成功！");
            return data.toJson();
        } catch (AuthenticationException e) {
            data.setStat(ResultData.STAT_FAILURE);
            data.setMessage("用户名或密码错误");
           return data.toJson();
      }
    }

    /**
     * @api {get} /logout  退出登录
     * @apiName logout
     * @apiGroup System-logincontroller
     */
    @GetMapping("/logout")
    String logout() {
        return "redirect:/login";
    }

}

